package com.link.common.util;

import io.netty.buffer.ByteBuf;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * 二进制数据转换工具类
 */
public class BinaryUtils {


    /**
     * 将二进制数据转换为字符串
     * @param buffer 二进制数据
     * @return 字符串
     */
    public static String toString(ByteBuffer buffer) {
        return new String(buffer.array(), StandardCharsets.UTF_8);
    }
    public static String readString(ByteBuf buffer) {
        int length=buffer.readInt();

        return   toString(buffer,length);
    }
    public static String toString(ByteBuf buffer, int length) {
       var array=new  byte[length];

        buffer.readBytes(array);

        return new String(array, StandardCharsets.UTF_8);

    }


    public static int getStringLength(String name) {
        return name.getBytes(StandardCharsets.UTF_8).length ;

    }

    public static void writeString(ByteBuf buffer, String name) {
        var array=name.getBytes(StandardCharsets.UTF_8);
        var length=array.length;
        buffer.writeInt(length);


        buffer.writeBytes(array);

    }
}